//
//  HMComposeViewController.swift
//  Weibo02
//
//  Created by teacher on 16/4/25.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 编辑微博界面视图
class HMComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    @objc private func didclickrightButton(){
        
        if pictureView.hidden {
            update()
        }else{
            upload()
        }
    }
    /// 发送图片微博
    private func upload(){
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数
        let params = [
            "access_token": AuthViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!,
      ]
        let data = UIImagePNGRepresentation(self.pictureView.images.first!)!

        NetWorkToolsAFN.sharedTolls.upload(urlString, parameters: params, datas: ["pic": data]) { (responseObject, error) -> () in
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
        
    }
    
    /// 发送文字微博
    private func update(){
        // 发送文字微博
        // 请求地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 请求参数
        let params = [
            "access_token": AuthViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!
        ]
        
        SVProgressHUD.showInfoWithStatus("正在发送………………")

        NetWorkToolsAFN.sharedTolls.request(RequestMethod.Post, url: urlString, parameters: params) { (responseObject, error) -> () in
            
//            SVProgressHUD.show("发送中")
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")

          self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    /// 选择图片
    private func selectPicture(){
        let vc = UIImagePickerController()
        vc.delegate = self
        // 判断 camera 是否可用
        //UIImagePickerController.isCameraDeviceAvailable(.Front)
        // 判断某个数据方式是否可用
        // UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType)
        // 如何去拍照？
        // vc.sourceType = .Camera
        // 裁剪图片
        // vc.allowsEditing = true
        self.presentViewController(vc, animated: true, completion: nil)
    }
    //设置视图
    private func setupUI(){
        ///  接收通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageframe:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //背景颜色
        view.backgroundColor = UIColor.whiteColor()
        //控制器左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        //界面标题
        navigationItem.titleView = titleView
        //设置右边的按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //默认关闭右边按钮的用户交互
        navigationItem.rightBarButtonItem?.enabled = false
        //添加底部stackview
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        
//        添加约束 textview
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        // ToolBar约束
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(10)
            make.top.equalTo(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
    }
    
    /// 切换键盘
    private func switchKeyboard(){
        
//        textView.inputAccessoryView = UIButton(type: UIButtonType.ContactAdd)
//        //判断当前是什么键盘 如果是系统键盘 就切换到表情键盘 否则切换到系统键盘
//        if textView.inputView == nil {
////            如果inputview等等与空 就是系统键盘 切换到表情键盘
//            textView.inputView = emoticonKeyboard
//        }else{
//            //切换到系统键盘
//            textView.inputView = nil
//        }
        
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        // 控制器告诉 toolBar 当前显示的是什么键盘
        composeToolBar.isSystemKeyboard = textView.inputView == nil
        // 重新加载输入的视图
        textView.reloadInputViews()
        if !textView.isFirstResponder() {
            textView.becomeFirstResponder()
        }
    }
    
    
    
    /**
     点击控制器左边按钮事件
     */
    @objc private func back(){
        //移除textview的第一响应者
        self.textView.resignFirstResponder()
        //移除当前控制器
        self.dismissViewControllerAnimated(true, completion: nil)
    }
 /// 键盘frame发生改变时接收到的通知
    @objc private func keyboardChageframe(noti: NSNotification){
//        keyBoard 键盘通知
//        键盘状态改变的时候,系统会发出一些特定的通知
//        UIKeyboardWillShowNotification // 键盘即将显示
//        UIKeyboardDidShowNotification // 键盘显示完毕
//        UIKeyboardWillHideNotification // 键盘即将隐藏
//        UIKeyboardDidHideNotification // 键盘隐藏完毕
//        UIKeyboardWillChangeFrameNotification // 键盘的位置尺寸即将发生改变
//        UIKeyboardDidChangeFrameNotification // 键盘的位置尺寸改变完毕
        //键盘的frame
        
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //toolbar的frame也要改变  更新约束 更新约束 更新约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
             //他底部的等于键盘Y值减去屏幕高度
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
        //设置动画时间
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    // MARK: - 懒加载控件
    //表情界面
    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        keyboard.frame.size = CGSize(width: SCREENW, height: 216)
        return keyboard
    }()
    ///navigationItem.titleView 界面标题
    lazy var titleView : UILabel = {
        let titleView = UILabel()
        // 指定行数
        titleView.numberOfLines = 0
        // 指定字体的颜色 大小
        titleView.textColor = UIColor.blackColor()
        titleView.font = UIFont.systemFontOfSize(14)
        // 设置文字居中
        titleView.textAlignment = .Center
        //如果 name 等于用户登录的名字
        if let name = AuthViewModel.sharedViewModel.account?.name {
            //let text = "发微博\n\(name)"
            let namexx = "\(name)"
            //let namex = NSMutableAttributedString(string: name)
            //求出name所在位置
            let range = (namexx as NSString).rangeOfString(name)
            //转换成 NSMutableAttributedString类型
            let attrText = NSMutableAttributedString(string: namexx)
            // 添加属性: 参数1：属性列表（字典类型），参数2：添加的范围
            attrText.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(20), NSStrokeWidthAttributeName: 2, NSStrokeColorAttributeName: UIColor.redColor()],range:range)
            // 设置富文本
            titleView.attributedText = attrText
        }else{
            titleView.text = "发微博"
        }
        titleView.sizeToFit()
        return titleView
    }()
    lazy var rightButton : UIButton = {
    
        //设置字体颜色
        let rightButton = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        //默认状态
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        // 设置不同状态下的背景图
        //关闭用户交互时
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        //默认状态
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        //高亮状态
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        // 设置不同状态的文字颜色
        //关闭用户交互时字体颜色
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        //按钮的frame
        rightButton.frame.size = CGSize(width: 45, height: 28)
        //监听按钮点击事件
        rightButton.addTarget(self, action: "didclickrightButton", forControlEvents: UIControlEvents.TouchUpInside)
        return rightButton
    }()
    /// ToolBar
    private lazy var composeToolBar : HMComposeToolBar = {
        let composeToolBar = HMComposeToolBar(frame: CGRectZero)
//        // 设置里面子控件点击要执行的闭包
//        composeToolBar.buttonClickClosure = { (type: HMComposeToolBarButtonType) in
//            print(type)
//            
        // 设置里面子控件点击要执行的闭包
            composeToolBar.buttonClickClosure = {[weak self] (type: HMComposeToolBarButtonType) in
                print(type)
                
                switch type {
                case .Picture:
                    self?.selectPicture()
                    break
                case .Mention:
                    break
                case .Trend:
                    break
                case .Emoticon:
                    self?.switchKeyboard()
                    break
                case .Add:
                    break
                }
            }
//            return composeToolBar
        
        return composeToolBar
    }()
   /// 加载textview
    private lazy var textView : HMTextView = {
        let textView = HMTextView()
        textView.placeholder = "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"
//        字体大小
        textView.font = UIFont.systemFontOfSize(16)
//        设置控制器为textView的代理
        textView.delegate = self
        // 拖动的时候消失键盘 (系统会弹出警告)
        textView.keyboardDismissMode = .OnDrag
        // 开启垂直方向的弹簧效果
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    private lazy var pictureView : HMComposePictureView = {
        let pictureView = HMComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        pictureView.selectedPictureClosure = {[weak self] in
            self?.selectPicture()
        }
        return pictureView
    }()
}
/// 延展 UITextViewDelegate的代理方法
extension HMComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        //当textView有值时 就不隐藏rightBarButtonItem 这样写可以省很多判断代码
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension HMComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 关闭当前界面
        //剪接的图片（宽度为600）
        let img = image.scaleToWidth(600)
        //
        let data = UIImagePNGRepresentation(img)
        //写入文件的路径
        data?.writeToFile("/Users/daiyazhou1/Desktop/\(random()/3).png", atomically: true)
        //给cell的image添加的图片
        pictureView.addImage(img)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}


